<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>修改密码</title>
    <link rel="stylesheet" href="../lib/layui/css/layui.css" />
    <link rel="stylesheet" href="../css/base.css" />
    <link rel="stylesheet" href="../css/form.css" />
  </head>

  <body>
    <div class="header container">
      修改密码
      <p style="display: block">
        <a href="./index.html">回到首页</a>
      </p>
    </div>
    <form>
      <span class="error">修改密码错误！</span>
      <label>
        原始密码： <input type="text" name="oldpassword" class="oldpassword" />
      </label>
      <label>
        新密码： <input type="text" name="newpassword" class="newpassword" />
      </label>
      <label>
        确认新密码：
        <input type="text" name="rnewpassword" class="rnewpassword" />
      </label>
      <button type="submit">确认修改</button>
    </form>
    <script src="../lib/jquery.js"></script>
    <script src="../lib/axios.js"></script>
    <script>
      $(document).ready(function () {
        $("form").on("submit", function (event) {
          event.preventDefault();
          var id = sessionStorage.getItem(id);
          var token = sessionStorage.getItem(token);
          var oldpassword = $(".oldpassword").val();
          var newpassword = $(".newpassword").val();
          var rnewpassword = $(".rnewpassword").val();

          if (!oldpassword || !newpassword || !rnewpassword) {
            alert("请填写所有必填项");
            return false;
          }

          if (newpassword !== rnewpassword) {
            alert("两次新密码输入不一致");
            return false;
          }

          axios
            .post(
              `http://localhost:9000/users/rpwd`,
              {
                id: sessionStorage.getItem("id"),
                oldPassword: oldpassword,
                newPassword: newpassword,
                rNewPassword: rnewpassword,
              },
              {
                headers: {
                  authorization: sessionStorage.getItem("token"),
                },
              }
            )
            .then(function (response) {
              if (response.data.code === 1) {
                alert(response.data.message);
                sessionStorage.clear();
                window.location.href = "./login.html";
              } else {
                alert(response.data.message);
              }
            })
            .catch(function (error) {
              alert("请求出错");
            });
        });
      });
    </script>
  </body>
</html>
